#include "widget.h"
#include "ui_widget.h"
#include "data.h"
#include <QTcpSocket>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_ptcpserver(new QTcpServer)
{
    ui->setupUi(this);

    init_network();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_network(){
    if (!m_ptcpserver->listen(QHostAddress::Any, 8099)){
        QMessageBox::information(this, "listen", "listen port fail");
        exit(1);
    }

    connect(m_ptcpserver, &QTcpServer::newConnection, this, &Widget::new_connection);

    return;
}

void Widget::new_connection(){
    QTcpSocket* ptcpsocket = m_ptcpserver->nextPendingConnection();

    connect(ptcpsocket, &QTcpSocket::readyRead, this, &Widget::ready_read);

    return;
}

void Widget::ready_read(){
    QTcpSocket* ptcpsocket = (QTcpSocket*)sender();

    QByteArray ba = ptcpsocket->readAll();
    QDataStream stream(&ba, QIODevice::ReadOnly);
    data_t dd;

    //反序列化
    stream >> dd.a >> dd.b;
    dd.ret = dd.a + dd.b;

    QMessageBox::information(this, "result", QString::number(dd.ret));

    QByteArray ba2;
    QDataStream stream2(&ba2, QIODevice::WriteOnly);
    //序列化
    stream2 << dd.a << dd.b << dd.ret;

    ptcpsocket->write(ba2);

    return;
}

